/*
 * 版权所有：义乌市路比信息科技有限公司
 * 作者：kinwyb<http://www.lcfgly.com>
 * 日期：2015-12-8
 */
package lcfgly.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import lcfgly.exception.LRunException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http请求封装
 *
 * @author kinwyb<http://www.lcfgly.com>
 * @datetime 2015-12-8 11:16:15
 * @version 1.0
 */
public class LHttpUtils {

    /**
     * POST请求
     * @param url
     * @param params
     * @return 
     */
    public static String Post(String url, Map<String, String> params) {
        HttpPost p = new HttpPost(url);
        if (params != null) {
            try {
                List<NameValuePair> nvps = new ArrayList<>();
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    String value = params.get(key);
                    NameValuePair pair = new BasicNameValuePair(key, value);
                    nvps.add(pair);
                }
                p.setEntity(new UrlEncodedFormEntity(nvps));
            } catch (UnsupportedEncodingException ex) {
                throw new LRunException("请求参数拼装异常",ex);
            }
        }
        try(CloseableHttpClient hclient=HttpClients.createDefault();)
        {
            try(CloseableHttpResponse response = hclient.execute(p);){
                return readResponse(response);
            }
        }catch(IOException e){
            throw new LRunException("HTTP请求失败",e);
        }
    }

    /**
     * 解析请求
     * @param response
     * @return 
     */
    private static String readResponse(CloseableHttpResponse response)throws IOException{
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        }
        throw new LRunException("HTTP请求失败：" + status);
    }
    
}
